package com.example.tests;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ContactCreationTests extends TestBase  {

	private static WebDriver driver;
	private String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();
	@BeforeTest
	public void setUp() throws Exception {
		driver = new FirefoxDriver();
		baseUrl = "http://localhost/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}
	
	@Test
	public void testForEmptyContact() throws Exception {
		openAddressBook();
		openPageForNewContact();
		fillContactForm(new ContactClass("", "", "", "", "", "", "9", "September", "1981", "Rob", "AddressT", "550"));
		submitNewContactForm();
		returnTOMainPage();
	}
	
	@Test
	public void testForValidContact() throws Exception {
		openAddressBook();
		openPageForNewContact();
		fillContactForm(new ContactClass("First nameT", "Last nameT", "AddressT", "12345", "67890", "email@gmail.com", "9", "September", "1981", "Rob", "AddressT", "550"));
		submitNewContactForm();
		returnTOMainPage();
	}

	private void returnTOMainPage() {
		//return to main page
		driver.findElement(By.linkText("home page")).click();
	}

	private void submitNewContactForm() {
		//submit new contact form
		driver.findElement(By.name("submit")).click();
	}

	private void fillContactForm(ContactClass parameterObject) {
		//fill contact form
		type2("firstname",parameterObject.firstName);
		type2("lastname",parameterObject.lastName);		
		type2("address",parameterObject.address);		
		type2("home",parameterObject.homePhone);
		type2("work",parameterObject.workPhone);
		type2("email",parameterObject.email);		
		select("bday", parameterObject.birthDay);
		select("bmonth", parameterObject.birthMonth);
		type2("byear",parameterObject.birthYear);
		select("new_group", parameterObject.groupName);
		type2("address2",parameterObject.address2);	
		type2("phone2",parameterObject.phone2);
		
	}

	private void select(String where, String what) {
		new Select(driver.findElement(By.name(where))).selectByVisibleText(what);
	}

	private void type2(String where, String what) {
		driver.findElement(By.name(where)).clear();
		driver.findElement(By.name(where)).sendKeys(what);
	}

	private void openPageForNewContact() {
		//open page for new contact
		driver.findElement(By.linkText("add new")).click();
	}

	private void openAddressBook() {
		//go to main page
		driver.get(baseUrl + "/");
		driver.findElement(By.linkText("addressbookv4.1.4")).click();
	}

	@AfterTest
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}


}



